package com.kevin.Code.Array;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Vinlee Xiao
 * @Classname SpiralMatrix
 * @Description Leetcode 54 螺旋矩阵 中等难度
 * @Date 2021/11/1 20:45
 * @Version 1.0
 */
public class SpiralMatrix {

    /**
     * @param matrix
     * @return
     */
    public List<Integer> spiralOrder(int[][] matrix) {

        int row = matrix.length;
        int col = matrix[0].length;

        int startIndex = 0;

        List<Integer> result = new ArrayList<>();

        //找出每次一圈循环的开始坐标
        while (row > 2 * startIndex && col > 2 * startIndex) {
            List<Integer> list = printMatrix(matrix, startIndex, row, col);
            result.addAll(list);
            startIndex++;
        }

        return result;
    }

    /**
     * @return
     */
    private List<Integer> printMatrix(int[][] matrix, int startIndex, int row, int col) {


        List<Integer> res = new ArrayList<>();
        //遍历结束的列
        int endX = col - startIndex - 1;
        //遍历结束的行
        int endY = row - startIndex - 1;

        //从左向右遍历
        for (int i = startIndex; i <= endX; i++) {
            res.add(matrix[startIndex][i]);
        }
        //从上往下遍历
        for (int i = startIndex + 1; i <= endY; i++) {
            res.add(matrix[i][endX]);
        }
        //从右往左 至少两列 两行
        if (endX > startIndex && endY > startIndex) {

            for (int i = endX - 1; i >= startIndex; i--) {
                res.add(matrix[endY][i]);
            }
        }
        //从下往上 至少两列三行
        if (endY > startIndex + 1 && endX > startIndex) {

            for (int i = endY - 1; i > startIndex; i--) {
                res.add(matrix[i][startIndex]);
            }
        }

        return res;
    }
}
